<template>
    <el-row class="wapper">
        <el-row class="title">发表新攻略</el-row>
        <el-row class="desc">分享你的个人游记，让更多人看到哦！</el-row>
        <el-row class="editorWapper">
            <el-row>
                <el-input v-model="title" placeholder="请输入标题"></el-input>
            </el-row>
            <el-row class="editor-box">
                <!-- 由于这个组件只有客户端才会引入
                所以也只能在客户端使用
                可以利用 nuxt 提供的标签 client-only
                声明一部分代码只在客户端处理 -->
                <client-only>
                    <vue-editor 
                    style="height:380px"
                    v-model="content"
                    :editorToolbar="customToolbar"
                    :useCustomImageHandler="true"
                    @image-added="imgUpload"
                    ></vue-editor>
                </client-only>
            </el-row>
            <el-row class="chooseCity">
                选择城市
                <el-autocomplete
                class="inline-input"
                v-model="city"
                :fetch-suggestions="querySearch"
                placeholder="请搜索游玩城市"
                :trigger-on-focus="false"
                :highlight-first-item ="true"
                ></el-autocomplete>
            </el-row>
            <el-row class="public">
                <el-button type="primary" size="small" @click="submitPost">发布</el-button>
                或者
                <span @click="saveDraft">保存到草稿</span>
            </el-row>
        </el-row>
    </el-row>
</template>

<script>
import moment from "moment"
export default {
    props:['draftFields'],
    data(){
        return{
            id:'',
            title:'',
            content:'',
            city:'',
            cityList:[],
            validCode:'0',
            customToolbar:[
                ['bold', 'italic', 'underline','strike'],
                [{'header': '1'},{'header': '2'}],
                ['image']
            ]
        }
    },
    watch:{
        draftFields(newVal,oldVal){
            if(newVal != null){
                const draftList = this.$store.state.draft.draftList;
                for(let i=0;i<draftList.length;i++){
                    if(draftList[i].id == newVal[0]){
                        this.id = newVal[0];
                        this.title = draftList[i].title;
                        this.content = draftList[i].content;
                        this.city = draftList[i].city;
                        this.date = newVal[1];
                    }
                }
            }
        }
    },
    methods:{
        querySearch(querystring,callback){
            this.getCityList(querystring);
            callback(this.cityList);
        },
        getCityList(querystring){
            this.$axios({
                url:'/airs/city',
                params:{name:querystring}
            }).then(res => {
                this.cityList = res.data.data.map(item => {
                    return {
                        value:item.name.replace(/市$/,''),
                        id:item.id
                    }
                });
            })
        },
        imgUpload(file, Editor, cursorLocation, resetUploader){
            // 这里是富文本框选择完图片会触发的函数
            // 带有四个参数 file, Editor, cursorLocation, resetUploader
            // file 选中的图片
            // Editor 是当前编辑器实例对象
            // cursorLocation 当前光标所在位置
            // resetUploader 这是上传完图片用来重新初始化上传功能的函数
            let formdata = new FormData();
            formdata.append('files',new Blob([file]));
            this.$axios({
                url:'/upload',
                method:'post',
                data:formdata
            }).then(res => {
                // Editor.insertEmbed() 这是编辑器自带函数, 可以往编辑框内放入内容
                // 三个参数 位置 / 类型 / 内容
                Editor.insertEmbed(cursorLocation, 'image', this.$axios.defaults.baseURL + res.data[0].url);
                // 将图片插入到富文本框之后还要重置上传功能
                resetUploader();
            })
        },
        submitPost(){
            // 判空
            if(!this.title){
                this.$message.warning('标题不能为空');
                return;
            }
            if(!this.content){
                this.$message.warning('内容不能为空');
                return;
            }
            if(!this.city){
               this.$message.warning('城市不能为空');
                return;
            }
            if(this.cityList.length <= 0){
                this.$message.warning('城市填写错误');
                return;
            }
            
            this.$axios({
                url:'/posts',
                method:'post',
                data:{
                   title:this.title,
                   content:this.content,
                   city:this.city
                },
                headers:{
                   Authorization:'Bearer ' + this.$store.state.user.userInfo.token
                }
            }).then(res => {
                if(res.data.message == '新增成功'){
                    this.$message.success(res.data.message);
                }
            })
            // 判断是否有id，有id则为草稿，需删除
            if(this.id){
               this.$store.commit('draft/delDraftInfo',this.id);
            }
            this.clearField();
        },
        saveDraft(){
            // 判空
            if(!this.title){
                this.$message.warning('标题不能为空');
                return;
            }
            if(!this.content){
                this.$message.warning('内容不能为空');
                return;
            }
            if(!this.city){
               this.$message.warning('城市不能为空');
                return;
            }
            if(this.cityList.length <= 0){
                this.$axios({
                url:'/airs/city',
                params:{name:this.city}
                }).then(res => {
                    this.cityList = res.data.data.map(item => {
                        return {
                            value:item.name.replace(/市$/,''),
                            id:item.id
                        }
                    });
                    if(this.cityList.length <= 0){
                        this.$message.warning('城市填写错误');
                    }
                })
                return;
            }
            // 无id情况新增，需去重
            if(!this.id){
                let flag = 0;
                let draftList = this.$store.state.draft.draftList;
                if(draftList.length > 0){
                    // 判重
                    for(let i=0;i<draftList.length;i++){
                        if(draftList[i].title == this.title 
                            && draftList[i].content == this.content 
                            && draftList[i].city == this.city){
                                flag = 1;
                                break;   
                        }
                    }
                }
                if(flag == 0){
                    // 添加到草稿记录list中
                    // 这里晚点使用moment.js
                    let obj = {
                        id:draftList.length > 0 ? draftList[0].id + 1 : 1,
                        title:this.title,
                        content:this.content,
                        city:this.city,
                        date:moment(new Date()).format("YYYY-MM-DD")
                    }
                    if(draftList.length >= 10){
                        this.$message.warning('只能保存最新的10个草稿文章');
                    }
                    this.$store.commit('draft/setDraftInfo',obj);
                }

            }else{
                let flag = 0;
                // 分两种情况
                // 一种有id直接保存（草稿删除导致）
                let objAdd = {
                    id:this.id,
                    title:this.title,
                    content:this.content,
                    city:this.city,
                    date:moment(new Date()).format("YYYY-MM-DD")
                }
                let draftList = this.$store.state.draft.draftList;
                if(draftList.length > 0){
                    for(let i=0;i<draftList.length;i++){
                        if(draftList[i].id == this.id){
                            // 更新
                            flag = 1;
                            break;
                        }
                    }
                }

                // 判断更新还是新增
                if(flag == 1){
                    let obj = {
                        id:this.id,
                        title:this.title,
                        content:this.content,
                        city:this.city,
                        date:moment(new Date()).format("YYYY-MM-DD")
                    }
                    this.$store.commit('draft/updateDraftInfo',obj);
                }else{
                    let objAdd = {
                        id:this.id,
                        title:this.title,
                        content:this.content,
                        city:this.city,
                        date:moment(new Date()).format("YYYY-MM-DD")
                    }
                    if(draftList.length >= 10){
                        this.$message.warning('只能保存最新的10个草稿文章');
                    }
                    this.$store.commit('draft/setDraftInfo',objAdd);
                }
            }
            this.clearField();
        },
        clearField(){
            this.id = null;
            this.title = '';
            this.content = '',
            this.city = '';
        }
    }
}
</script>

<style lang="less" scoped>
.wapper{
    width: 750px;
    .title{
        font-size: 22px;
    }
    .desc{
        margin:10px 0 8px;
        font-size: 12px;
        color: #999999;
    }
    .editorWapper{
        .editor-box{
            margin:20px 0;
            height: 458px;
        }
        .chooseCity{
            margin:20px 0;
            font-size: 13px;
            color: #5F6266;
            .el-autocomplete{
                margin-left: 12px;
            }
        }
        .public{
            margin-bottom: 20px;
            font-size: 14px;
            .el-button{
               margin-right: 16px;
            }
            span{
                color: #FFB500;
                cursor: pointer;
            }
        }
    }
}
</style>